package com.ys.chatserver.http.logic;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.eva.epc.common.util.CommonUtils;
import com.eva.framework.Processor;
import com.eva.framework.dto.SysActionConst;
import com.eva.framework.utils.EndsExceptionFactory;
import com.google.gson.Gson;
import com.ys.chatserver.common.dto.cnst.RetResult;
import com.ys.chatserver.common.dto.cnst.RtcRedisKeyConstants;
import com.ys.chatserver.common.dto.cnst.UserProtocalsType;
import com.ys.chatserver.http.logic.dto.*;
import com.ys.chatserver.im.util.MessageHelper;
import com.ys.chatserver.redis.RedisUtil;
import com.ys.chatserver.tool.EmptyUtils;
import com.ys.chatserver.tool.IdUtils;
import com.ys.chatserver.tool.MD5Util;
import net.ys.mobileimsdk.server.processor.OnlineProcessor;

import java.util.*;

public class DevInfoProccessor implements SysActionConst, Processor {
    private Gson gson = new Gson();

    @Override
    public Object process(int job_dispatch_id, int action_id, Object newData, Object oldData, User user) throws Exception {
        Object ret = null;
        String newDataJSON = (String) newData;

        // 处理后台用户管理
        if (job_dispatch_id == JobDispatchConst.LOGIC_GROUP_DEV) {
            ret = maintainUserJobDispatcher(action_id, newDataJSON, oldData, user);
        } else {
            throw EndsExceptionFactory.INVALID_JOB_DISPATCHER_ID(job_dispatch_id);
        }
        return ret;
    }

    private Object maintainUserJobDispatcher(int actionId, String newDataJSON, Object oldData, User user) throws Exception {
        int role = getAccountType(user.getUserId());
        switch (actionId) {
            case ACTION_ADD_USER: //添加设备
            {
                if (role != 0 && role != 2) {
                    return gson.toJson(RetResult.failResult("暂无权限！"));
                }
                JSONObject jsonObj = JSONObject.parseObject(newDataJSON);
                String userMail = jsonObj.getString("userMail");
                String nickname = jsonObj.getString("nickname");
                String userPsw = jsonObj.getString("userPsw");
                Date registerTime = new Date();
                Integer userStatus = 1;
                String expireTime = jsonObj.getString("expireTime");
                String devType = jsonObj.getString("devType");
                if (EmptyUtils.isEmpty(userMail) || EmptyUtils.isEmpty(nickname) || EmptyUtils.isEmpty(userPsw) ||
                        EmptyUtils.isEmpty(devType) || EmptyUtils.isEmpty(expireTime)) {
                    return gson.toJson(RetResult.failResult("参数错误!"));
                }
                UserInfoDTO dto = getUserByUserMail(userMail);
                //设备且在表被逻辑删除  直接启用
                if (!Objects.isNull(dto)) {
                    if (dto.getDelFlag() == 1) {
                        return updateUserDelFlag(userMail);
                    }
                }
                if (exitMail(userMail)) {
                    return gson.toJson(RetResult.failResult("设备名已存在！"));
                }
                if (userPsw.length() < 6 || userPsw.length() > 18) {
                    return gson.toJson(RetResult.failResult("密码长度6~18位！"));
                }
                if (userPsw.matches("[0-9]+")) {
                    return gson.toJson(RetResult.failResult("密码必须包含数字、字母或特殊符号！"));
                }
                userPsw = MD5Util.MD5_32(userPsw);
                List<String> sqls = new ArrayList<>(2);
                List<Object[]> values = new ArrayList<>(2);
                addDevInfo(sqls, values, userMail, nickname, userPsw, registerTime, userStatus,
                        "1", devType, expireTime, user.getUserId());

                boolean update = LogicProcessor2.db.update(sqls, values, true);
                if (update) {
                    Vector<Vector<?>> vector1 = LogicProcessor2.db.queryData("select user_uid from g_users where del_flag = 0 and user_mail='" + userMail + "' limit 1");
                    LogicProcessor2.db.update("insert into my_gb28181 (dev_id) values (?)", new String[]{vector1.get(0).get(0).toString()}, true);

                }
                return update ? gson.toJson(RetResult.successResult("添加成功!")) : gson.toJson(RetResult.failResult("添加失败!系统异常!"));
            }
            case ACTION_QUERY_USER: { //获取设备列表
                if (role != 0 && role != 2) {
                    return gson.toJson(RetResult.failResult("暂无权限！"));
                }
                JSONObject jsonObj = JSON.parseObject(newDataJSON);
                Integer pageSize = Integer.valueOf(jsonObj.getString("pageSize"));
                Integer pageNumber = Integer.valueOf(jsonObj.getString("pageNumber"));
                String keyword = jsonObj.getString("keyword");
                return queryDevList(user.getUserId(), pageSize, pageNumber, keyword);
            }
            case ACTION_UPDATE_USER: { //修改设备信息
                if (role != 0 && role != 2) {
                    return gson.toJson(RetResult.failResult("暂无权限！"));
                }
                UpdateDevVO vo = JSON.parseObject(newDataJSON, UpdateDevVO.class);
                if (EmptyUtils.isEmpty(vo.getDevId())) {
                    return gson.toJson(RetResult.failResult("设备不存在"));
                }
                if (getAccountType(user.getUserId()) == null) {
                    return gson.toJson(RetResult.failResult("设备不存在"));
                }
                List<String> sqlList = getSqlList(vo);
                boolean update = LogicProcessor2.db.update(sqlList, true);
                return update ? gson.toJson(RetResult.successResult("修改成功!")) : gson.toJson(RetResult.failResult("修改失败!系统异常!"));
            }
            case ACTION_DELETE_USER: { //删除设备信息
                if (role != 0 && role != 2) {
                    return gson.toJson(RetResult.failResult("暂无权限！"));
                }
                JSONObject jsonObj = JSON.parseObject(newDataJSON);
                final String devId = jsonObj.getString("devId");
                Vector<Vector<?>> vector = LogicProcessor2.db.queryData("select * from structure_user_info where user_id='" + devId + "' and is_finish=0");
                if (!vector.isEmpty()) {
                    return gson.toJson(RetResult.failResult("该设备有尚未完结的AJ,无法删除!"));
                }
                return deleteUser(devId, user.getUserId());
            }
            case ACTION_QUERY_USER_INFO: { //查询设备信息
                JSONObject jsonObj = JSON.parseObject(newDataJSON);
                final String devId = jsonObj.getString("devId");
                return queryDevById(devId);
            }
            case ACTION_UPDATE_USER_PASSWORD: { //修改设备密码
                if (role != 0 && role != 2) {
                    return gson.toJson(RetResult.failResult("暂无权限！"));
                }
                JSONObject jsonObj = JSON.parseObject(newDataJSON);
                final String devId = jsonObj.getString("devId");
                String userPsw = jsonObj.getString("userPsw");
                if (userPsw.length() < 6 || userPsw.length() > 18) {
                    return gson.toJson(RetResult.failResult("密码长度6~18位！"));
                }
                if (userPsw.matches("[0-9]+")) {
                    return gson.toJson(RetResult.failResult("密码必须包含数字、字母或特殊符号！"));
                }
                userPsw = MD5Util.MD5_32(userPsw);
                return updateUserPassword(devId, userPsw, user.getUserId());
            }
            case ACTION_CONSOLE_CONTROLLER: {
                JSONObject jsonObj = JSON.parseObject(newDataJSON);
                String userUid = jsonObj.getString("devId");
                if (LogicProcessor2.db.queryData("select user_type from g_users where user_uid = '" + userUid + "' and del_flag is false ").get(0).get(0).toString().equals("1")) {
                    if (OnlineProcessor.isOnline(userUid)) {
                        Integer type = jsonObj.getInteger("type");
                        String value = jsonObj.getString("value");
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("type", type);
                        jsonObject.put("value", value);
                        MessageHelper.sendMessage(userUid, jsonObject.toString(), false, UserProtocalsType.ACTION_CONSOLE_CMD, null);
                        return gson.toJson(RetResult.successResult("设置成功"));
                    } else {
                        return gson.toJson(RetResult.failResult("设备离线"));
                    }
                } else {
                    return gson.toJson(RetResult.failResult("该对象不是正确的设备类型"));
                }
            }
            case ACTION_QUERY_DEVICE_ENV:
                JSONObject ect = JSON.parseObject(newDataJSON);
                return RedisUtil.get(RtcRedisKeyConstants.DEV_ENV_KEY + ect.getString("devId"));

            default:
                throw EndsExceptionFactory.INVALID_ACTION_ID(actionId);
        }
    }

    private String updateUserDelFlag(String userMail) throws Exception {
        String sql = "update g_users set  del_flag = 0 where user_mail = '" + userMail + "'";
        List<String> strings = new ArrayList<>();
        strings.add(sql);
        boolean update = LogicProcessor2.db.update(strings, true);
        return update ? gson.toJson(RetResult.successResult("添加成功!")) : gson.toJson(RetResult.failResult("添加失败!系统异常!"));

    }

    private UserInfoDTO getUserByUserMail(String userMail) throws Exception {
        String sql = "select user_mail,del_flag from  g_users where del_flag = 0 and user_mail = '" + userMail + "'";
        Vector<Vector<?>> vectors = LogicProcessor2.db.queryData(sql);

        if (vectors.isEmpty()) {
            return null;
        }
        UserInfoDTO dto = new UserInfoDTO();
        for (Vector<?> vector : vectors) {
            dto.setUserMail(userMail);
            dto.setDelFlag(Integer.parseInt(vector.get(1).toString()));
        }
        return dto;
    }

    private String updateUserPassword(String devId, String userPsw, String operateId) throws Exception {
        String createId = getCreateId(devId);
        if (createId == null || !createId.equals(operateId)) {
            return gson.toJson(RetResult.failResult("暂无权限!"));
        }
        String sql = "update g_users set  user_psw = '" + userPsw + "' where del_flag = 0 and user_uid = '" + devId + "'";
        List<String> strings = new ArrayList<>();
        strings.add(sql);
        boolean update = LogicProcessor2.db.update(strings, true);

        return update ? gson.toJson(RetResult.successResult("修改成功!")) :
                gson.toJson(RetResult.failResult("修改失败!系统异常!"));

    }

    private String queryDevById(String devId) throws Exception {
        String s = "select u.nickname,u.register_time,u.latest_login_time,u.dev_type,u.expire_time," +
                " u.user_uid,u.user_mail,u.user_status,g.nickname creatorName,u.is_online" +
                "  from g_users u " +
                " left join g_users g on g.user_uid = u.creator_id " +
                " where u.del_flag = 0 and u.user_uid = '" + devId +
                "' and u.user_type=1";
        Vector<Vector<?>> vectors = LogicProcessor2.db.queryData(s);
        QueryUserResVO vo = new QueryUserResVO();
        if (vectors.isEmpty()) {
            vo.setUserUid("-1");
            return new Gson().toJson(RetResult.failResult("账号不存在!"));
        }

        for (Vector<?> v : vectors) {
            int i = 0;
            String nickname = v.get(i).toString();
            String registerTime = v.get(++i).toString();
            String latestLoginTime = v.get(++i).toString();
            String type = v.get(++i).toString();
            String expireTime = v.get(++i).toString();
            String uid = v.get(++i).toString();
            String userMail = v.get(++i).toString();
            String userStatus = v.get(++i).toString();
            String creatorName = v.get(++i).toString();
            Integer isOnline = Integer.valueOf(v.get(++i).toString());
            vo.setUserUid(uid);
            vo.setNickname(nickname);
            vo.setRegisterTime(registerTime);
            vo.setDevType(Integer.valueOf(type));
            vo.setLatestLoginTime(latestLoginTime);
            vo.setExpireTime(expireTime);
            vo.setUserMail(userMail);
            vo.setUserStatus(Integer.valueOf(userStatus));
            vo.setCreatorName(creatorName);
            vo.setIsOnline(isOnline);
        }

        return gson.toJson(RetResult.successResult("查询成功!", vo));
    }

    /**
     * 删除设备
     *
     * @param devId     设备ID
     * @param operateId 操作人Id
     */
    private String deleteUser(String devId, String operateId) throws Exception {
        //查询修改人是否为创建者
        String createId = getCreateId(devId);
        if (createId == null || !createId.equals(operateId)) {
            return gson.toJson(RetResult.failResult("暂无权限!"));
        }

        //查询设备是否存在
        QueryUserResVO vo = getDevByCreatorId(devId, operateId);
        if ("-1".equals(vo.getUserUid())) {
            return gson.toJson(RetResult.failResult("删除的账号不存在!"));
        }
        //设备
        if (vo.getUserType() == 1) {
            List<String> list = new ArrayList<>();

            String s = "update g_users set del_flag = 1 where user_uid = '" + devId + "'";
            list.add(s);
            boolean update = LogicProcessor2.db.update(list, true);
            return update ? gson.toJson(RetResult.successResult("删除成功!")) : gson.toJson(RetResult.failResult("删除失败!系统异常!"));
        }

        return gson.toJson(RetResult.failResult("删除失败!"));
    }

    private List<String> getSqlList(UpdateDevVO vo) {
        List<String> sqlList = new ArrayList<>();
        StringBuilder builder = new StringBuilder();
        builder.append("update g_users set");
        if (EmptyUtils.isNotEmpty(vo.getNickname())) {
            builder.append(" nickname = '" + vo.getNickname() + "',");
        }
        if (EmptyUtils.isNotEmpty(vo.getUserStatus())) {
            builder.append(" user_status = '" + vo.getUserStatus() + "',");
        }
        if (EmptyUtils.isNotEmpty(vo.getDevType())) {
            builder.append(" dev_type = '" + vo.getDevType() + "',");
        }
        if (EmptyUtils.isNotEmpty(vo.getDownloadUrl())) {
            builder.append(" download_url = '" + vo.getDownloadUrl() + "',");
        }
        if (EmptyUtils.isNotEmpty(vo.getExpireTime())) {
            builder.append(" expire_time = '" + vo.getExpireTime() + "'");
        }

        builder.append(" where del_flag = 0 and user_uid = '" + vo.getDevId() + "'");
        builder.append(" and user_type=1");
        sqlList.add(builder.toString());
        return sqlList;
    }

    private String queryDevList(String userUid, Integer pageSize, Integer pageNumber, String keyword) throws Exception {
        Integer accountType = getAccountType(userUid);
        String sql = "select u.nickname,u.register_time,u.latest_login_time,u.dev_type,u.expire_time" +
                ",g.nickname creatorName,u.user_uid from g_users u " +
                " left join g_users g on g.user_uid = u.creator_id" +
                " where u.del_flag = 0" +
                " and u.user_type=1";
        if (accountType == 2) {
        } else if (accountType == 0) {
            sql += " and u.creator_id = '" + userUid + "'";
        } else {
            return gson.toJson(RetResult.failResult("无权限查看!"));
        }
        if (!CommonUtils.isStringEmpty(keyword)) {
            sql += " and (u.nickname like '%" + keyword + "%' or u.user_uid like '%" + keyword + "%')";

        }
        if (!Objects.isNull(pageNumber) && pageNumber > 0) {
            Integer pageNum = countPageNumber(pageNumber, pageSize);
            sql += " limit " + pageNum + "," + pageSize;
        }

        Long total = 0L;
        StringBuilder builder = new StringBuilder();
        builder.append("select count(*) from g_users where del_flag = 0 and user_type=1");
        if (accountType == 0) {
            builder.append(" and creator_id = '" + userUid + "'");
        }
        if (!CommonUtils.isStringEmpty(keyword)) {
            builder.append(" and (nickname like '%" + keyword + "%' or user_uid like '%" + keyword + "%')");
        }
        Vector<Vector<?>> count = LogicProcessor2.db.queryData(builder.toString());
        if (!count.isEmpty()) {
            total = Long.valueOf((String) count.get(0).get(0));
        }


        Vector<Vector<?>> list = LogicProcessor2.db.queryData(sql);
        List<QueryUserResVO> vos = new ArrayList<>();
        for (Vector<?> v : list) {
            QueryUserResVO vo = new QueryUserResVO();
            int i = 0;
            String nickname = v.get(i).toString();
            String registerTime = v.get(++i).toString();
            String latestLoginTime = v.get(++i).toString();
            String type = v.get(++i).toString();
            String expireTime = v.get(++i).toString();
            String creatorName = v.get(++i).toString();
            String uid = v.get(++i).toString();
            vo.setUserUid(uid);
            vo.setNickname(nickname);
            vo.setRegisterTime(registerTime);
            vo.setDevType(Integer.valueOf(type));
            vo.setLatestLoginTime(latestLoginTime);
            vo.setExpireTime(expireTime);
            vo.setCreatorName(creatorName);
            vos.add(vo);
        }
        PageData<QueryUserResVO> pageData = new PageData<>();
        pageData.setRecords(vos);
        pageData.setTotal(total);
        pageData.setPageNumber(pageNumber);
        pageData.setPageSize(list.size());
        return gson.toJson(RetResult.successResult("获取成功！", pageData));
    }

    private String getCreateId(String userUid) throws Exception {
        String s = "select creator_id from g_users where del_flag = 0 and user_uid = '" + userUid + "'";
        Vector<Vector<?>> vectors = LogicProcessor2.db.queryData(s);
        if (vectors.isEmpty()) {
            return null;
        }
        return (String) vectors.get(0).get(0);
    }

    private Integer getAccountType(String userUid) throws Exception {
        String s = "select account_type from g_users where del_flag = 0 and user_uid = '" + userUid + "'";
        Vector<Vector<?>> vectors = LogicProcessor2.db.queryData(s);
        if (vectors.isEmpty()) {
            return null;
        }
        return Integer.valueOf(vectors.get(0).get(0).toString());
    }

    private QueryUserResVO getDevByCreatorId(String userUid, String creatorId) throws Exception {
        String s = "select nickname,register_time,latest_login_time,dev_type,expire_time," +
                "user_uid,user_type  from g_users where del_flag = 0 and creator_id = '" + creatorId + "' and user_uid = '" + userUid + "' and user_type = 1";
        Vector<Vector<?>> vectors = LogicProcessor2.db.queryData(s);
        QueryUserResVO vo = new QueryUserResVO();
        if (vectors.isEmpty()) {
            vo.setUserUid("-1");
            return vo;
        }

        for (Vector<?> v : vectors) {
            int i = 0;
            String nickname = v.get(i).toString();
            String registerTime = v.get(++i).toString();
            String latestLoginTime = v.get(++i).toString();
            String type = v.get(++i).toString();
            String expireTime = v.get(++i).toString();
            String uid = v.get(++i).toString();
            String userType = v.get(++i).toString();
            vo.setUserUid(uid);
            vo.setNickname(nickname);
            vo.setRegisterTime(registerTime);
            vo.setDevType(Integer.valueOf(type));
            vo.setLatestLoginTime(latestLoginTime);
            vo.setExpireTime(expireTime);
            vo.setUserType(Integer.valueOf(userType));
        }

        return vo;
    }

    private Integer countPageNumber(Integer pageNumber, Integer pagrSize) {
        return (pageNumber - 1) * pagrSize;
    }


    private void addDevInfo(List<String> sqls, List<Object[]> values, String userMail, String nickname,
                            String userPsw, Date registerTime, Integer userStatus,
                            String userType, String devType, String expireTime, String creatorId) {
        String sql = "insert into g_users (user_uid,user_mail,nickname,user_psw,register_time,user_status," +
                "user_type,dev_type,expire_time,creator_id) values (?,?,?,?,?,?,?,?,?,?)";
        sqls.add(sql);
        values.add(new Object[]{IdUtils.get8Uuid(), userMail, nickname, userPsw,
                registerTime, userStatus, userType, devType, expireTime, creatorId});
    }

    /**
     * 判断添加账户名是否存在
     */
    private boolean exitMail(String userMail) throws Exception {
        String sql = "select * from g_users where del_flag = 0 and user_mail='" + userMail + "'";
        Vector<Vector<?>> vectors = LogicProcessor2.db.queryData(sql);
        return !vectors.isEmpty();
    }


}
